package com.yuan.yblog.common.service;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.yuan.yblog.common.consts.RedisKey;
import com.yuan.yblog.common.exception.Asserts;
import com.yuan.yblog.common.pojo.VerificationCodeImg;
import com.yuan.yblog.common.utils.StringUtils;
import com.yuan.yblog.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 验证码服务类
 */

@Service
public class CaptchaService {

    @Autowired
    RedisService redisService;

    /**
     * 生成验证码
     * @return base64格式的图片数据
     */
    public VerificationCodeImg generateCaptcha() {
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(150, 38,4,50);
        VerificationCodeImg verificationCodeImg = VerificationCodeImg.createBase64Img(lineCaptcha);

        // 存入缓存
        redisService.set(RedisKey.CAPTCHA + verificationCodeImg.getCaptchaId(),
                lineCaptcha.getCode(),
                RedisKey.CAPTCHA_EXPIRE);
        verificationCodeImg.setExpire(RedisKey.CAPTCHA_EXPIRE);

        // 返回结果
        return verificationCodeImg;
    }

    /**
     * 校验 验证码
     * @param captcha 前端的验证码
     * @param captchaId 验证码标识
     */
    public Boolean verifyCaptcha(String captchaId , String captcha) {
        if(exist(captchaId)) {
            return false;
        }
        String key = RedisKey.CAPTCHA + captchaId;
        String redisCaptcha = (String) redisService.get(key);
        if(!captcha.equals(redisCaptcha)){
            return false;
        }
        //验证成功，删除验证码
        redisService.del(key);
        return true;
    }

    /**
     * 刷新 验证码
     * @param captchaId 验证码id
     */
    public VerificationCodeImg refreshCaptcha(String captchaId) {
        if (!exist(captchaId)) {
            Asserts.fail("验证码已失效/不存在");
        }
        // 删除
        redisService.del(RedisKey.CAPTCHA + captchaId);
        // 重新生成
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(150, 38,4,50);
        VerificationCodeImg newImage = VerificationCodeImg.createBase64Img(lineCaptcha);
        newImage.setCaptchaId(captchaId);
        // 重新配置
        redisService.set(RedisKey.CAPTCHA + newImage.getCaptchaId(),
                lineCaptcha.getCode(),
                RedisKey.CAPTCHA_EXPIRE);
        return newImage;
    }

    /**
     * 判断指定验证码是否有效
     * @param captchaId 验证码id
     * @return true表示有效
     */
    public boolean exist(String captchaId) {
        if (StringUtils.isEmpty(captchaId)) {
            return false;
        }
        // 1秒内视为已过期
        return redisService.hasKey(RedisKey.CAPTCHA + captchaId) && redisService.getExpire(RedisKey.CAPTCHA + captchaId) > 1L;
    }

}
